package com.mocha.mybatis.pojo;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.mocha.common.core.IMochaQuery;

/**
 * @author: songkui
 * @date: 2022/6/22 10:29
 */
public abstract class MybatisQuery<T> implements IMochaQuery<T> {

    protected long total = 0;
    protected long size = 20;
    protected long current = 1;
    protected String orderASC;
    protected String orderDESC;

    protected boolean searchCount;  //默认 是total 大于0 则fasle 否则true

    protected abstract void buildOrderASC();  //将前端传入的 查询条件 转换成sql 条件；  比如: 前端传 id， name;  u.id; u.name;
    protected abstract void buildOrderDESC();


    public Page<T> buildPage(){
        buildOrderASC();
        buildOrderDESC();
        Page<T> page = PageDTO.of(this.current, this.size, this.total, searchCount);
        if (StrUtil.isNotEmpty(orderASC)){
            page.addOrder(OrderItem.ascs(orderASC.split(",")));
        }else if (StrUtil.isNotEmpty(orderDESC)){
            page.addOrder(OrderItem.descs(orderDESC.split(",")));
        }
        return page;
    }

    public Page<T> buildPage(String asc, String desc){
        Page<T> page = PageDTO.of(this.current, this.size, this.total, searchCount);
        if (StrUtil.isNotEmpty(asc)){
            page.addOrder(OrderItem.ascs(asc.split(",")));
        }else if (StrUtil.isNotEmpty(desc)){
            page.addOrder(OrderItem.descs(desc.split(",")));
        }
        return page;
    }

    public void setSearchCount(boolean searchCount) {
        this.searchCount = searchCount;
    }

    @Override
    public long getTotal() {
        return this.total;
    }

    @Override
    public long getSize() {
        return this.size;
    }

    @Override
    public long getCurrent() {
        return this.current;
    }

    @Override
    public String getOrderASC() {
        return this.orderASC;
    }

    @Override
    public String getOrderDESC() {
        return this.orderDESC;
    }

    @Override
    public IMochaQuery<T> setTotal(long total) {
        this.total = total;
        this.searchCount = this.total > 0 ? false : true;
        return this;
    }

    @Override
    public IMochaQuery<T> setSize(long size) {
        this.size = size;
        return this;
    }

    @Override
    public IMochaQuery<T> setCurrent(long current) {
        this.current = current;
        return this;
    }

    @Override
    public IMochaQuery<T> setOrderASC(String orderASC) {
        this.orderASC = orderASC;
        return this;
    }

    @Override
    public IMochaQuery<T> setOrderDESC(String orderDESC) {
        this.orderDESC = orderDESC;
        return this;
    }
}
